<template>
    <div class="upload-file">
        <input type="file" class="hide" ref="fileInput" @change="inputChange"/>
        <div class="upload-button" @click="uploadFile">
            <slot/>
        </div>
    </div>
</template>

<script>
    /* eslint-disable no-undef */

    export default {
        name: 'upload-file',
        data () {
            return {
                file: this.value
            };
        },
        props: {
            value: {type: String},
            url: {type: String, required: true}
        },
        watch: {
            file (val) {
                this.$emit('input', val);
            },
            value (val) {
                this.file = val;
            }
        },
        methods: {
            uploadFile () {
                $(this.$refs.fileInput).click();
            },
            inputChange (e) {
                let data = new FormData();
                data.append('file', e.srcElement.files[0]);
                axios.post(this.url, data, {header: {'Content-Type': 'multipart/form-data'}}).then(res => {
                    if (res.data.success === false) return this.$notify.error(res.data.data);
                    this.file = res.data.data;
                });
            }
        }
    };
</script>

<style scoped lang="scss">
    .upload-file {
        display: inline-block;
    }
</style>
